﻿using KwaiXiaoDian.Entity.VO.Notice;
using KwaiXiaoDian.IService;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using SSharing.Frameworks.NetCore.Common.Extends;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Linq;
using System.Linq.Expressions;

namespace KwaiXiaoDian.Service
{
    public class NoticeService : INoticeService
    {
        private readonly IConfiguration _configuration;
        private readonly ILogger<NoticeService> _logger;
        private readonly IHttpClientFactory _httpclient;

        public NoticeService(IConfiguration configuration
            , ILogger<NoticeService> logger
            , IHttpClientFactory httpclient)
        {
            _configuration = configuration;
            _logger = logger;
            _httpclient = httpclient;
        }

        /// <summary>
        /// server酱
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public bool SendServerChan(SendServerChanRequest request, bool isOnlyAdmin = false)
        {
            var result = false;
            List<string> sendKeys = new List<string>();

            //读取Server酱的配置
            var serverChanSection = _configuration.GetSection("ServerChan");
            var serverChanHost = serverChanSection["Endpoint"].TrimEnd('/');
            var serverChanMultipleSendKey = serverChanSection["MultipleSendKey"];
            if (!serverChanMultipleSendKey.IsNullOrEmpty())
            {
                var multipleSendKeys = serverChanMultipleSendKey.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                sendKeys.AddRange(multipleSendKeys);
            }
            if (isOnlyAdmin)
            {
                var serverChanAdminSendKey = serverChanSection["AdminSendKey"];
                sendKeys.Clear();
                sendKeys.Add(serverChanAdminSendKey);
            }

            //https://sctapi.ftqq.com/<SENDKEY>.send
            var postData = CreatePostData(request);
            foreach (var sendKey in sendKeys)
            {
                var requestUrl = string.Format(serverChanHost + "/{0}.send", sendKey);
                var sendServerChanResponse = Send(requestUrl, postData);
                if (sendServerChanResponse != null && sendServerChanResponse.errno == 0)
                {
                    result = true;
                }
            }

            return result;
        }

        #region Private method

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        private SendServerChanResponse Send(string url, string postData, string contentType = "application/x-www-form-urlencoded")
        {
            SendServerChanResponse sendServerChanResponse = null;

            try
            {
                var content = new StringContent(postData, Encoding.UTF8, contentType);
                var _client = _httpclient.CreateClient();
                var response = _client.PostAsync(url, content).Result;
                if (response.IsSuccessStatusCode)
                {
                    Task<string> t = response.Content.ReadAsStringAsync();
                    if (t != null)
                    {
                        sendServerChanResponse = t.Result.FromJson<SendServerChanResponse>();
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, string.Format("通过Server酱发送消息时发生异常，message:{0}", ex.Message));
            }

            return sendServerChanResponse;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        private string CreatePostData(SendServerChanRequest request)
        {
            var formData = new List<string>();
            formData.Add("title=" + request.Text);
            formData.Add("desp=" + request.Desp);

            return string.Join("&", formData);
        }
        #endregion
    }
}
